import React, { useState, useRef, useEffect, useCallback, useMemo } from 'react';
import { Tabs, Button, FloatButton, message } from 'antd';
import {
  EditOutlined,
  EyeOutlined,
  ToolOutlined,
  ArrowLeftOutlined,
  SaveOutlined,
  DownOutlined,
  FireOutlined,
  MenuOutlined,
} from '@ant-design/icons';
import { useBreakpoint } from '../../../hooks/useBreakpoint';
import { useAutoSave } from '../../../hooks/useAutoSave';
import { Show, Hide } from '../../Responsive/ResponsiveExports';
import MarkdownRenderer from '../../conversation/MarkdownRenderer';
import MarkdownToolbar from '../MarkdownToolbar';
import MobileMarkdownToolbar from '../MobileMarkdownToolbar';
import ResponsiveOptimizationPanel from '../../optimization/ResponsiveOptimizationPanel';
import ResponsiveHotTopicPanel from '../../conversation/HotTopicPanel/ResponsiveHotTopicPanel';
import './style.css';

interface ResponsiveMarkdownEditorProps {
  value: string;
  onChange: (value: string) => void;
  onSave?: () => void;
  onBack?: () => void;
  title?: string;
  showOptimization?: boolean;
  showHotTopic?: boolean;
  autoSaveKey?: string; // localStorage key for auto-save
  enableAutoSave?: boolean;
}

const ResponsiveMarkdownEditor: React.FC<ResponsiveMarkdownEditorProps> = ({
  value,
  onChange,
  onSave,
  onBack,
  title = '编辑文章',
  showOptimization = true,
  showHotTopic = true,
  autoSaveKey = 'markdown-editor-draft',
  enableAutoSave = true,
}) => {
  const breakpoint = useBreakpoint();
  const isMobile = breakpoint === 'mobile';

  // 抽屉可见性状态
  const [hotTopicVisible, setHotTopicVisible] = useState(false);
  const [optimizationVisible, setOptimizationVisible] = useState(false);

  // 自动保存功能
  const { restoreDraft, clearDraft, manualSave } = useAutoSave(value, {
    key: autoSaveKey,
    delay: 30000, // 30秒
    enabled: enableAutoSave,
  });

  // 组件挂载时恢复草稿
  useEffect(() => {
    if (enableAutoSave && !value) {
      const draft = restoreDraft();
      if (draft) {
        onChange(draft);
        message.info('已恢复上次编辑的内容');
      }
    }
  }, []); // eslint-disable-line react-hooks/exhaustive-deps

  const [activeTab, setActiveTab] = useState('edit');
  const [showScrollButton, setShowScrollButton] = useState(false);
  const textareaRef = useRef<HTMLTextAreaElement>(null);
  const previewRef = useRef<HTMLDivElement>(null);
  const scrollPositionsRef = useRef<Record<string, number>>({});

  // 防抖处理onChange
  const debouncedOnChange = useMemo(
    () => {
      let timeout: NodeJS.Timeout;
      return (newValue: string) => {
        clearTimeout(timeout);
        timeout = setTimeout(() => onChange(newValue), 300);
      };
    },
    [onChange]
  );

  // 移动端键盘适配
  useEffect(() => {
    if (isMobile && textareaRef.current) {
      const handleFocus = () => {
        setTimeout(() => {
          textareaRef.current?.scrollIntoView({ behavior: 'smooth', block: 'center' });
        }, 300);
      };

      textareaRef.current.addEventListener('focus', handleFocus);
      return () => textareaRef.current?.removeEventListener('focus', handleFocus);
    }
  }, [isMobile]);

  // 保存和恢复滚动位置
  const saveScrollPosition = useCallback(() => {
    const element = activeTab === 'edit' ? textareaRef.current : previewRef.current;
    if (element) {
      scrollPositionsRef.current[activeTab] = element.scrollTop;
    }
  }, [activeTab]);

  const restoreScrollPosition = useCallback((tab: string) => {
    setTimeout(() => {
      const element = tab === 'edit' ? textareaRef.current : previewRef.current;
      const savedPosition = scrollPositionsRef.current[tab];
      if (element && savedPosition !== undefined) {
        element.scrollTop = savedPosition;
      }
    }, 50); // 延迟以确保内容已渲染
  }, []);

  // 检测是否显示滚动到顶部按钮
  const handleScroll = useCallback(() => {
    const element = activeTab === 'edit' ? textareaRef.current : previewRef.current;
    if (element) {
      setShowScrollButton(element.scrollTop > 300);
      saveScrollPosition();
    }
  }, [activeTab, saveScrollPosition]);

  useEffect(() => {
    const element = activeTab === 'edit' ? textareaRef.current : previewRef.current;
    if (element) {
      element.addEventListener('scroll', handleScroll);
      return () => element.removeEventListener('scroll', handleScroll);
    }
  }, [activeTab, handleScroll]);

  const scrollToTop = () => {
    const element = activeTab === 'edit' ? textareaRef.current : previewRef.current;
    element?.scrollTo({ top: 0, behavior: 'smooth' });
  };

  // 手势滑动切换Tab
  const [touchStart, setTouchStart] = useState(0);
  const [touchEnd, setTouchEnd] = useState(0);

  const handleTouchStart = (e: React.TouchEvent) => {
    setTouchStart(e.touches[0].clientX);
  };

  const handleTouchMove = (e: React.TouchEvent) => {
    setTouchEnd(e.touches[0].clientX);
  };

  const handleTouchEnd = () => {
    if (!isMobile) return;

    const diff = touchStart - touchEnd;
    const threshold = 50;

    if (Math.abs(diff) > threshold) {
      const tabs = showOptimization ? ['edit', 'preview', 'optimize'] : ['edit', 'preview'];
      const currentIndex = tabs.indexOf(activeTab);

      if (diff > 0 && currentIndex < tabs.length - 1) {
        // 左滑，下一个Tab
        saveScrollPosition();
        const newTab = tabs[currentIndex + 1];
        setActiveTab(newTab);
        restoreScrollPosition(newTab);
      } else if (diff < 0 && currentIndex > 0) {
        // 右滑，上一个Tab
        saveScrollPosition();
        const newTab = tabs[currentIndex - 1];
        setActiveTab(newTab);
        restoreScrollPosition(newTab);
      }
    }

    setTouchStart(0);
    setTouchEnd(0);
  };

  const tabItems = [
    {
      key: 'edit',
      label: (
        <span className="flex items-center gap-2">
          <EditOutlined />
          <span className={isMobile ? 'text-mobile-sm' : ''}>编辑</span>
        </span>
      ),
      children: (
        <div className="editor-pane">
          {!isMobile && <MarkdownToolbar textareaRef={textareaRef} value={value} onChange={onChange} />}

          <textarea
            ref={textareaRef}
            className={`markdown-editor ${isMobile ? 'mobile' : ''}`}
            value={value}
            onChange={(e) => {
              onChange(e.target.value);
              debouncedOnChange(e.target.value);
            }}
            placeholder="在此输入Markdown内容..."
            spellCheck={false}
            autoCapitalize="off"
            autoCorrect="off"
          />

          {isMobile && <MobileMarkdownToolbar textareaRef={textareaRef} value={value} onChange={onChange} />}
        </div>
      ),
    },
    {
      key: 'preview',
      label: (
        <span className="flex items-center gap-2">
          <EyeOutlined />
          <span className={isMobile ? 'text-mobile-sm' : ''}>预览</span>
        </span>
      ),
      children: (
        <div ref={previewRef} className={`preview-pane ${isMobile ? 'mobile' : ''}`}>
          <MarkdownRenderer content={value} />
        </div>
      ),
    },
  ];

  if (showOptimization && isMobile) {
    // 移动端：点击优化Tab时打开抽屉
    tabItems.push({
      key: 'optimize',
      label: (
        <span
          className="flex items-center gap-2"
          onClick={(e) => {
            e.preventDefault();
            setOptimizationVisible(true);
          }}
        >
          <ToolOutlined />
          <span className="text-mobile-sm">优化</span>
        </span>
      ),
      children: (
        <div className="optimization-placeholder mobile">
          <Button
            type="primary"
            icon={<ToolOutlined />}
            onClick={() => setOptimizationVisible(true)}
            size="large"
            className="h-touch"
          >
            打开内容优化
          </Button>
        </div>
      ),
    });
  }

  return (
    <div className="responsive-markdown-editor">
      {/* 移动端顶部工具栏 */}
      <Show breakpoint="mobile">
        <div className="mobile-editor-header">
          {onBack && (
            <Button
              type="text"
              icon={<ArrowLeftOutlined />}
              onClick={onBack}
              className="h-touch w-touch"
            />
          )}
          <h2 className="text-mobile-base font-bold flex-1">{title}</h2>
          <Space>
            {showHotTopic && (
              <Button
                type="text"
                icon={<FireOutlined />}
                onClick={() => setHotTopicVisible(true)}
                className="h-touch w-touch"
              />
            )}
            {onSave && (
              <Button
                type="primary"
                icon={<SaveOutlined />}
                onClick={() => {
                  manualSave();
                  onSave();
                  clearDraft(); // 保存后清除草稿
                }}
                className="h-touch"
                style={{ minHeight: '44px' }}
              >
                保存
              </Button>
            )}
          </Space>
        </div>
      </Show>

      {/* 桌面端：左右双栏布局 */}
      <Hide breakpoint="mobile">
        <div className="desktop-editor-layout">
          <div className="editor-column">
            <MarkdownToolbar textareaRef={textareaRef} value={value} onChange={onChange} />
            <textarea
              ref={textareaRef}
              className="markdown-editor"
              value={value}
              onChange={(e) => {
                onChange(e.target.value);
                debouncedOnChange(e.target.value);
              }}
              placeholder="在此输入Markdown内容..."
              spellCheck={false}
              autoCapitalize="off"
              autoCorrect="off"
            />
          </div>
          <div className="preview-column">
            <div className="preview-header">
              <h3>预览</h3>
            </div>
            <div ref={previewRef} className="preview-pane">
              <MarkdownRenderer content={value} />
            </div>
          </div>
        </div>
      </Hide>

      {/* 移动端：Tab切换布局 */}
      <Show breakpoint="mobile">
        <div
          className="mobile-editor-tabs"
          onTouchStart={handleTouchStart}
          onTouchMove={handleTouchMove}
          onTouchEnd={handleTouchEnd}
        >
          <Tabs
            activeKey={activeTab}
            onChange={(key) => {
              saveScrollPosition();
              setActiveTab(key);
              restoreScrollPosition(key);
            }}
            items={tabItems}
            className="h-full"
          />
        </div>
      </Show>

      {/* 滚动到顶部按钮 */}
      {showScrollButton && (
        <FloatButton
          icon={<DownOutlined style={{ transform: 'rotate(180deg)' }} />}
          onClick={scrollToTop}
          style={{
            right: isMobile ? 16 : 24,
            bottom: isMobile ? 80 : 24,
            width: isMobile ? 56 : 40,
            height: isMobile ? 56 : 40,
          }}
        />
      )}

      {/* 移动端热点创作抽屉 */}
      {isMobile && showHotTopic && (
        <ResponsiveHotTopicPanel
          visible={hotTopicVisible}
          onClose={() => setHotTopicVisible(false)}
        />
      )}

      {/* 移动端优化面板抽屉 */}
      {isMobile && showOptimization && (
        <ResponsiveOptimizationPanel
          content={value}
          title={title}
          onOptimized={onChange}
          visible={optimizationVisible}
          onClose={() => setOptimizationVisible(false)}
        />
      )}

      {/* 桌面端侧边栏：热点面板 */}
      {!isMobile && showHotTopic && (
        <div className="desktop-sidebar-right">
          <ResponsiveHotTopicPanel visible={true} />
        </div>
      )}

      {/* 桌面端：优化面板作为Tab的一部分在主区域 */}
      {!isMobile && showOptimization && (
        <div className="desktop-optimization-section" style={{ display: 'none' }}>
          <ResponsiveOptimizationPanel
            content={value}
            title={title}
            onOptimized={onChange}
            visible={true}
          />
        </div>
      )}
    </div>
  );
};

export default ResponsiveMarkdownEditor;
